#!/usr/bin/env python

import gtk
import gtk.glade

import gnomevfs

import pango

import os 

import uspCoreUtils

from utils.IconFactory import IconFactory
from utils.GConfigurator import GConfigurator

from xdg.DesktopEntry import *

import utils.ButtonFactory as uspButtonFactory

class RecentView(object):
	def __init__(self, recentBox, clearButton):
		self.recentBox = recentBox
		self.manager = gtk.recent_manager_get_default()
		self.manager.connect("changed", self.onRecentChanged)
		
		self.iconFactory = IconFactory()
		self.toolTips = gtk.Tooltips()
		self.buttonFactory = self.createButtonFactory()
		
		clearButton.connect("clicked", self.onClearButtonClicked)
		
		self.refresh()
	
	def createButtonFactory(self):
		buttonFactory = uspButtonFactory.ButtonFactory()
		buttonFactory.iconSize = gtk.ICON_SIZE_BUTTON
		buttonFactory.minLabelWidth = 20
		buttonFactory.labelAlignment = 0.5
		buttonFactory.toolTipWidget = self.toolTips
		
		buttonFactory.clearLabelAttributes()
		buttonFactory.addLabelAttribute(pango.AttrWeight(pango.WEIGHT_NORMAL, 0, -1))
		buttonFactory.addLabelAttribute(pango.AttrWeight(pango.WEIGHT_NORMAL, 0, -1))
		
		return buttonFactory
	
	def recentSortCriterium(self, item1, item2):
		return cmp(item2.get_added(), item1.get_added())
		
	def refresh(self):
		uspCoreUtils.clearWidgetChildren(self.recentBox)
		
		limit = Configuration().recentGClient.getInteger('recent_files_limit', 10)
		
		items = [i for i in self.manager.get_items() if i.exists() and i.is_local()]
		items.sort(self.recentSortCriterium)
		
		for index, item in enumerate(items):
			if index >= limit:
				break
			uri = item.get_uri()
			path = gnomevfs.get_local_path_from_uri(uri)
			if path.endswith(".desktop"):
				desktopItem = DesktopEntry(path)
				icon = desktopItem.getIcon()
				name = desktopItem.getName()
				executeLine = desktopItem.getExec()
				tooltipText = executeLine
				self.buttonFactory.addEvent("button_release_event", self.onButtonClicked, uspCoreUtils.removeArgs(executeLine.split()))
				button = self.buttonFactory.create([name], icon, tooltipText)
				self.recentBox.pack_start(button, False, False, 0)
			else:
				name = item.get_display_name()
				tooltipText = path + "\n" + str(item.get_age()) + " days old"
				self.buttonFactory.addEvent("button_release_event", self.onButtonClicked, ['xdg-open', uri])
				button = self.buttonFactory.create([name], self.iconFactory.iconForURI(uri, 24, True, True), tooltipText)
				self.recentBox.pack_start(button, False, False, 0)
				
	def onRecentChanged(self, manager):
		self.refresh()
	
	def onButtonClicked(self, widget, event, commandLine):
		uspCoreUtils.execute(commandLine)
	
	def onClearButtonClicked(self, widget):
		self.manager.purge_items()
		
class Configuration(uspCoreUtils.Singleton):
	def __init__(self):
		uspCoreUtils.Singleton.__init__(self)
		
class UspPlugin(object):
	gladeFilename = "uspRecent.glade"
	
	def __init__(self):
		self.gladefile = os.path.join(os.path.dirname(__file__) , self.gladeFilename)
		
		if not os.path.exists(self.gladefile):
			raise Exception("Glade file '"+ self.gladeFilename +"' does not exist.")
			
		self.widgetTree = gtk.glade.XML(self.gladefile, "MainWindow")
		self.window = self.widgetTree.get_widget("MainWindow")
		self.contentHolder = self.widgetTree.get_widget("MainEventBox")
		
		self.gClient = GConfigurator('/apps/usp2/plugins/recent')
		Configuration().recentGClient = self.gClient
		
		recentBox = self.widgetTree.get_widget("RecentBox1")
		clearButton = self.widgetTree.get_widget("ClearButton1")
		
		self.userView = RecentView(recentBox, clearButton)
	
	def pluginName(self):
		return "Recent"
	
	def mainWidget(self):
		return self.contentHolder
	
	def pluginIcon(self):
		return 'gnome-system'
	
	def getPluginSize(self):
		width = self.gClient.getInteger('width', 100)
		height = self.gClient.getInteger('height', 250)
		return width, height
	
	def setPluginSize(self, width, height):
		self.gClient.setInteger('width', width)
		self.gClient.setInteger('height', height)
	
	def getOptions(self):
		return [['Recent files limit', 'int', self.gClient.getInteger('recent_files_limit', 10)] ]
		
	def setOptions(self, options):
		self.gClient.setInteger('recent_files_limit', options[0][2])
		self.userView.refresh()
		
